package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.WebSocket.WebSocketServer;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Override
    @Transactional
    public OrderSubmitVO OrdeSubmit(OrdersSubmitDTO ordersSubmitDTO) {
        //判断业务异常（用户地址簿为空，用户购物车为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        ShoppingCart shoppingCart = new ShoppingCart();
        Long userid = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.getShoppingCart(userid);
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPhone(addressBook.getPhone());
        orders.setStatus(orders.PENDING_PAYMENT);
        orders.setPayStatus(orders.UN_PAID);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userid);
        orders.setAddress(addressBook.getDetail());

        orderMapper.insert(orders);
        //向订单详细表插入多条数据
        List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();//订单明细
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());//当前订单明细管关联的订单id
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);
        //清空购物车
        shoppingCartMapper.clean();
        //封装VO对象
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .orderTime(orders.getOrderTime())
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

      /*  //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }*/

        String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
        String nonceStr = RandomStringUtils.randomNumeric(32);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("nonceStr", nonceStr);
        jsonObject.put("timeStamp", timeStamp);
        jsonObject.put("packge","prepay_id="+12345678);
        jsonObject.put("signType","RSA");
        jsonObject.put("paySign","okkkk");

        return jsonObject.toJavaObject(OrderPaymentVO.class);
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        Map map = new HashMap();
        map.put("type",1);
        map.put("OrderId",orders.getId());
        map.put("content","订单号："+outTradeNo);
       String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 历史订单查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult selectHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.querryOrders(ordersPageQueryDTO);
        List<OrderVO> orders = orderMapper.select(ordersPageQueryDTO.getStatus());
        for (OrderVO order : orders) {
            order.setOrderDetailList(orderDetailMapper.querryOrdersDetail(order.getId()));
        }
        return new  PageResult(page.getTotal(),orders);
    }

    /**
     *  历史订单详情查询
      * @param id
     * @return
     */
    @Override
    public OrderVO selcetOrderDetail(Long id) {
        OrderVO orderVO = orderMapper.selectOrderDetail(id);
        orderVO.setOrderDetailList(orderDetailMapper.querryOrdersDetail(id));
/*        AddressBook addressBook = addressBookMapper.getById(orderVO.getAddressBookId());
        orderVO.setAddress(addressBook.getDetail());*/
        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cencel(Long id) {
        Orders orders = orderMapper.selectOrderDetail(id);
        //检验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if (orders.getStatus() == orders.UN_PAID || orders.getStatus() == orders.TO_BE_CONFIRMED ){
            orders.setStatus(orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason("用户取消");
            orderMapper.update(orders);
        }else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

    }

    @Override
    public void repetition(Long id) {
        //查询用户id
        Long userId = BaseContext.getCurrentId();
        //根据订单id查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.querryOrdersDetail(id);
        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetails.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);

    }

    /**
     * 管理端订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.conditionSearch(ordersPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     *  商家接单
     * @param
     */
    @Override
    public void orderconfirm(OrdersConfirmDTO ordersConfirmDTO) {
        orderMapper.orderconfirm(ordersConfirmDTO);
    }

    /**
     * 商家拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void orderRejection(OrdersRejectionDTO ordersRejectionDTO) {
        orderMapper.orderRejection(ordersRejectionDTO);
    }

    /**
     *  订单派送
     * @param id
     */
    @Override
    public void orderdelivery(Integer id) {
        orderMapper.orderdelivery(id);
    }

    /**
     * 订单完成
     * @param id
     */
    @Override
    public void ordercomplete(Integer id) {
        orderMapper.ordercomplete(id);
    }

    @Override
    public void ordercancel(OrdersCancelDTO ordersCancelDTO) {
        orderMapper.ordercancel(ordersCancelDTO);
    }

    /**
     * 各个订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO getStatistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(getByStatus(Orders.CONFIRMED).size());
        orderStatisticsVO.setToBeConfirmed(getByStatus(Orders.TO_BE_CONFIRMED).size());
        orderStatisticsVO.setDeliveryInProgress(getByStatus(Orders.DELIVERY_IN_PROGRESS).size()) ;
        return orderStatisticsVO;
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Integer id) {
        Orders ordersDb = orderMapper.getById(id);
        if (ordersDb == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map = new HashMap();
        map.put("type",2);
        map.put("OrderId",ordersDb.getId());
        map.put("content","订单号："+ordersDb.getNumber());
        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    private List<Orders> getByStatus(Integer status) {
       List<Orders> orders = orderMapper.getByStatus(status);
        return orders;
    }
}
